package fm.yichenet.controller;

import com.mongodb.DBObject;
import fm.controller.BaseController;
import fm.dto.NeiyiUser;
import fm.exception.BizException;
import fm.util.CommonUtils;
import fm.web.CurrentRequest;
import fm.yichenet.mongo.service.ExpressService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by CM on 2017/6/27.
 */
@Controller
@RequestMapping("/express")
public class ExpressController extends BaseController {
    @Autowired
    private ExpressService expressService;

    @ResponseBody
    @RequestMapping("/list")
    public Map getExpressListByShop(String shopId,String goodId, String province) {
        Map res = new HashMap();
        try {
            if (shopId == null && goodId == null) {
                throw new BizException("店铺Id和商品Id不能同时为空!");
            }

            List<DBObject> expresses;
            if(CommonUtils.isEmpty(goodId)){
                expresses = expressService.getExpressList(null, shopId, province);
                if (CollectionUtils.isEmpty(expresses)) {
                    expresses = expressService.getExpressList(null, shopId, "default");
                }
            }else{
                expresses = expressService.getExpressListByGoodId(goodId,shopId,province);
            }

            res.put("data", expresses);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping("/one")
    public Map getExpress(String expressId) {
        Map res = new HashMap();
        try {
            DBObject express = expressService.getExpress(expressId);
            res.put("data", express);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }
}
